import json

from channels.generic.websocket import AsyncWebsocketConsumer

from account.trade import get_goods_price
from system.market import get_market_orders


class MarketConsumer(AsyncWebsocketConsumer):

    async def connect(self):
        await self.channel_layer.group_add(
            'market',
            self.channel_name
        )
        await self.accept()

    async def receive(self, text_data=None):
        jo = json.loads(text_data)
        typ = jo.get('type')
        data = jo.get('data')
        if typ == 'goods_price':  # 获取商品最新价
            goods_sn = data
            price = get_goods_price(goods_sn)
            resp = {
                'type': typ,
                'data': {
                    'symbol': goods_sn,
                    'price': price
                }
            }
            await self.send(text_data=json.dumps(resp))
        elif typ == 'market_orders':  # 获取市场委托订单
            orders = get_market_orders(data)
            resp = {
                'type': typ,
                'data': orders
            }
            await self.send(text_data=json.dumps(resp))

    async def goods_price(self, event):
        data = event['data']
        text_data = ''
        if type(data) == dict:
            text_data = json.dumps({
                'type': 'goods_price',
                'data': data
            })
        await self.send(text_data=text_data)

    async def market_orders(self, event):
        data = event['data']
        orders = get_market_orders(data)
        text_data = ''
        if type(data) == dict:
            text_data = json.dumps({
                'type': 'market_orders',
                'data': orders
            })
        await self.send(text_data=text_data)
